package com.zmh.service.http;

import java.io.IOException;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zmh.common.DateUtil;
import com.zmh.common.RandomUtil;
import com.zmh.dao.WorklogMapper;
import com.zmh.entity.MailEntity;
import com.zmh.entity.WorklogEntity;
import com.zmh.service.http.utils.HttpAPIService;
import com.zmh.service.http.utils.HttpResult;
import com.zmh.service.msg.MailService;

/** 
 * 工作日志管理，提醒日志填写，自动批阅日志
 * @author: zhoumh
 * @version: 创建时间：2018年8月15日 下午5:13:23 
 * @Description: 
 * 2018-11-05 09:47 履职审阅系统更新，每个请求增加版本、系统等关键字段 
*/ 
@Service
public class WorklogHttp {
	private static Logger logger = LoggerFactory.getLogger(WorklogHttp.class);
	private static String token = "";
	@Autowired
	private HttpAPIService httpAPIService;
	@Autowired
	private MailService mailService;
	@Autowired
	private WorklogMapper worklogMapper;

	/**
	 * 登陆IamtopNotes
	 * @author zhoumh
	 * @version 创建时间：2018年8月15日 下午5:13:23 
	 * @throws Exception 
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public boolean login() throws Exception{
		JSONObject params = new JSONObject();
		params.put("act", "ACT_LOGIN");
		params.put("api", "LoginCheck");
		params.put("regionCode", "371300");
		params.put("regionId", 1);
		params.put("username", "zhouminghao");
		params.put("password", "123456");
		params.put("appVer", "4.2.4");
		params.put("termType", 0);
		params.put("systemType", "Win32");
		JSONObject login = new JSONObject();
		login.put("method", 2);
		login.put("cmd", "ACT_LOGIN");
		login.put("params", params);
		//{"method":2,"cmd":"ACT_LOGIN","params":{"act":"ACT_LOGIN","api":"LoginCheck","regionCode":"371300","regionId":1,"username":"zhouminghao","password":"123456"}}
		//{"method":2,"cmd":"ACT_LOGIN","params":{"act":"ACT_LOGIN","api":"LoginCheck","regionCode":"371300","regionId":1,"username":"zhouminghao","password":"123456","appVer":"4.2.4","termType":0,"systemType":"Win32"}}
		// 发起登陆请求
		HttpResult result = httpAPIService.doPostJson("http://123.132.252.2:23180/api/v1/LoginCheck", login.toJSONString());
		JSONObject body = JSONObject.parseObject(result.getBody().toString());
		if (result.getCode()==200&&body.getInteger("ErrCode")==0) {
			logger.info("worklog登录成功！");
			// 获取token
			return getToken(body.getJSONObject("Values").getString("token"));
		}
		return false;
	}
	/**
	 * 获取token
	 * @author zhoumh
	 * @version 创建时间：2018年8月15日 下午5:13:23 
	 * @throws Exception 
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public boolean getToken(String t) throws Exception{
		JSONObject params = new JSONObject();
		params.put("api", "organ");
		params.put("act", "organ");
		params.put("appVer", "4.2.4");
		params.put("termType", 0);
		params.put("systemType", "Win32");
		params.put("token", t);
		JSONObject login = new JSONObject();
		login.put("method", 2);
		login.put("cmd", "organ");
		login.put("params", params);
		//{"method":2,"cmd":"organ","params":{"api":"organ","act":"organ","token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJmZTEwMWRjZS1hZjM1LTRhM2EtYTgzNy05NTk2N2FmZmU5NjUiLCJyZWdpb25Db2RlIjoiMzcxMzAwIiwicmVnaW9uSWQiOjEsIm9yZ2FuSWQiOjEsImRlcGFydElkIjozMywiZXhwIjoxNTM1MDY4Mzc1LCJ1c2VySWQiOjgxOSwidGltZU91dCI6MTcyODAwfQ.jwWyk7yZrgNIlWjCBxpr_VLb46JAtIb1iZnyiXw5Sz-gs8hpdeS48r9MUqwGa7AOV7TvKZcU-wlmrV72ZOVJtA"}}
		// 发起请求
		HttpResult result = httpAPIService.doPostJson("http://123.132.252.2:23180/api/v1/organ", login.toJSONString());
		JSONObject body = JSONObject.parseObject(result.getBody().toString());
		if (result.getCode()==200) {
			return refToken(body);
//			logger.info("获取token成功："+token);
		}
		return false;
	}
	/**
	 * 获取全部工作
	 * @return: void
	 * @author: zhoumh
	 * @version: 创建时间：2018年8月15日 下午5:13:23 
	 * @throws Exception 
	 * @Description:
	 */
	public void getAllNotes() throws Exception {
		//登陆验证
		if (StringUtils.isEmpty(token) || !login()) {
			//如果登陆失败终止后续程序执行
			logger.error("登陆notes失败，本次运行终止。");
			return;
		}
		String url = "http://notes.iamtop.com:64023/work/a/bus/workReview/findReviews?pageNo=1&pageSize=5&type=allReviewed&busUser.id=58&_="+System.currentTimeMillis();
		JSONObject page = JSON.parseObject(httpAPIService.doGet(url)).getJSONObject("page");
		int i = 0;
		if (page.getInteger("total")>0) {
			//如果还有未处理的待审批工作事项
			while (i++<page.getIntValue("pageCount")) {
				System.out.println("http://notes.iamtop.com:64023/work/a/bus/workReview/findReviews?pageNo="+i+"&pageSize=5&type=allReviewed&busUser.id=58&_="+System.currentTimeMillis());
				JSONObject weiyue = JSON.parseObject(httpAPIService.doGet("http://notes.iamtop.com:64023/work/a/bus/workReview/findReviews?pageNo="+i+"&pageSize=5&type=allReviewed&busUser.id=58&_="+System.currentTimeMillis()));
				JSONArray notes = weiyue.getJSONArray("list");
				for (int j = 0; j < notes.size(); j++) {
					JSONObject note = notes.getJSONObject(j);
					JSONArray workLogList = note.getJSONArray("workLogList");
					for (int k = 0; k < workLogList.size(); k++) {
						WorklogEntity worklogEntity = new WorklogEntity();
						worklogEntity.setInDate(note.getString("inDate"));
						JSONObject workLog = workLogList.getJSONObject(k);
						worklogEntity.setFirstName(workLog.getJSONObject("firstClass").getString("name"));
						worklogEntity.setSecondName(workLog.getJSONObject("secondClass").getString("name"));
						worklogEntity.setBusName(workLog.getJSONObject("busClass").getString("name"));
						worklogEntity.setComment(workLog.getString("comment"));
						worklogEntity.setCreateTime(workLog.getString("createDate"));
						worklogEntity.setUpdateTime(workLog.getString("updateDate"));
						worklogEntity.setCostTime(workLog.getString("costTime"));
						worklogMapper.insert(worklogEntity);
					}
				}
			}
		}
		
	}
	/**
	 * 获取未阅工作
	 * @return: void
	 * @author: zhoumh
	 * @version: 创建时间：2018年8月15日 下午5:13:23 
	 * @throws Exception 
	 * @Description:
	 */
	public void getWeiYueNotes() throws Exception {
		//登陆验证
		if (!login()) {
			//如果登陆失败终止后续程序执行
			logger.error("登陆notes失败，本次运行终止。");
			return;
		}
		JSONObject params = new JSONObject();
		params.put("api", "worklogreview");
		params.put("act", "reviewList");
		params.put("selectedUserId", null);
		params.put("selectedOrganId", null);
		params.put("selectedDepartId", null);
		params.put("pageNo", 1);
		params.put("pageSize", 10);
		params.put("token", token);
		params.put("appVer", "4.2.4");
		params.put("termType", 0);
		params.put("systemType", "Win32");
		JSONObject post = new JSONObject();
		post.put("method", 2);
		post.put("cmd", "reviewList");
		post.put("params", params);
		JSONObject reviewPage = JSON.parseObject(httpAPIService.doPostJson("http://123.132.252.2:23180/api/v1/worklogreview", JSONObject.toJSONString(post,SerializerFeature.WriteMapNullValue)).getBody());
		JSONObject values = reviewPage.getJSONObject("Values");
		if(!refToken(reviewPage)) return; //返回代码有错，终止执行
		String[] names = new String[] {"汤世凤","刘彦交","肖东山","韩爱荣","梁见"};
		String content = "今日工作日志如下： \n";
		Integer total = values.getInteger("total");
		//未阅日志条数大于0
		if (total>0) {
			//循环分页，判断时间在今天之前
			int i = 0;
			while (i++<=total%10) {
				params.put("pageNo", i);
				//token是根据时间生成的，为了防止处理时间过长导致token发生变化，每次提交都重置token
				params.put("token", token);
				reviewPage = JSON.parseObject(httpAPIService.doPostJson("http://123.132.252.2:23180/api/v1/worklogreview", JSONObject.toJSONString(post,SerializerFeature.WriteMapNullValue)).getBody());
				if(!refToken(reviewPage)) break; //更新token 返回代码有错，终止执行
				JSONArray reviewList = reviewPage.getJSONObject("Values").getJSONArray("reviewList");
				for (int j = 0; j < reviewList.size(); j++) {
					JSONObject review = reviewList.getJSONObject(j);
					if (DateUtil.getDayDiff(review.getString("reportDate")+":000")>=3) {
						continue;
					}
					String name = review.getString("name");
					String logDate = review.getString("logDate");
					if (logDate.equals(DateUtil.getDate())) {
						//如果当天已提交日志，就从成员数组中移除
						names = ArrayUtils.removeElement(names, name);
					}
					content = content.concat("\n"+name+" ");
					content = content.concat(logDate+" ");
					content = content.concat(review.getString("week")+" \n");
					JSONArray logItems = review.getJSONArray("logItems");
					for (int k = 0; k < logItems.size(); k++) {
						JSONObject logItem = logItems.getJSONObject(k);
						content = content.concat(k+1+"、"+logItem.getString("classType")+": ");
//						content = content.concat(logItem.getString("dutyOutline")+"： ");
						content = content.concat(logItem.getString("content")+" ");
						content = content.concat("（用时："+logItem.getString("costTime")+"小时） \n");
					}
				}
			}
			if (ArrayUtils.isNotEmpty(names)) {
				//如果还有未提交日志的就增加提醒信息
				String tmp = "还有如下人员未提交日志： \n"+StringUtils.join(names,", \n")+"\n";
				content = StringUtils.join(tmp,content);
			}
		}else {
			content = DateUtil.getDate()+" 未发现待审批工作事项！";
		}
		//由于日志系统的问题，超时未审批事项会一直存在，需要过滤这部分
		if (content.equals("今日工作日志如下： \n")) {
			content = DateUtil.getDate()+" 未发现待审批工作事项！";
		}
		logger.info(content);
        mailService.saveMail(new MailEntity("工作日志<zhoumh1985@qq.com>", "zmh1812@qq.com", DateUtil.getDate()+"工作日志汇总", content,"sendSimpleMail"));
	}
	/**
	 * 获取未阅工作并设置为已阅
	 * @return: void
	 * @author: zhoumh
	 * @version: 创建时间：2018年8月15日 下午5:13:23 
	 * @throws Exception 
	 * @Description:
	 */
	public void workLogShenyue() throws Exception {
		//登陆验证
		if (!login()) {
			//如果登陆失败终止后续程序执行
			logger.error("登陆notes失败，本次运行终止。");
			return;
		}
		JSONObject params = new JSONObject();
		params.put("api", "worklogreview");
		params.put("act", "reviewList");
		params.put("selectedUserId", null);
		params.put("selectedOrganId", null);
		params.put("selectedDepartId", null);
		params.put("pageNo", 1);
		params.put("pageSize", 10);
		params.put("token", token);
		params.put("appVer", "4.2.4");
		params.put("termType", 0);
		params.put("systemType", "Win32");
		JSONObject post = new JSONObject();
		post.put("method", 2);
		post.put("cmd", "reviewList");
		post.put("params", params);
		JSONObject reviewPage = JSON.parseObject(httpAPIService.doPostJson("http://123.132.252.2:23180/api/v1/worklogreview", JSONObject.toJSONString(post,SerializerFeature.WriteMapNullValue)).getBody());
		if(!refToken(reviewPage)) return; //更新token 返回代码有错，终止执行
		JSONObject values = reviewPage.getJSONObject("Values");
		Integer total = values.getInteger("total");
		//循环分页，判断时间在今天之前
		int i = 0;
		String err = ""; 
		while (i++<=total%10) {
			params.put("pageNo", i);
			params.put("token", token);
			reviewPage = JSON.parseObject(httpAPIService.doPostJson("http://123.132.252.2:23180/api/v1/worklogreview", JSONObject.toJSONString(post,SerializerFeature.WriteMapNullValue)).getBody());
			if(!refToken(reviewPage)) break; //更新token 返回代码有错，终止执行
			JSONArray reviewList = reviewPage.getJSONObject("Values").getJSONArray("reviewList");
			for (int j = 0; j < reviewList.size(); j++) {
				JSONObject review = reviewList.getJSONObject(j);
				if (DateUtil.getDayDiff(review.getString("reportDate")+":000")>=3) {
					continue;
				}
				Thread.sleep(1000*(RandomUtil.getRandomBy10()+5));
				JSONObject result = JSON.parseObject(saveReview(review));
				if (result.getString("Info").indexOf("日志评分完成")>-1) {
					if(!refToken(result)) break; //更新token 返回代码有错，终止执行
					logger.info("日志审阅成功！"+review.toString());
				}else{
					// {"ErrCode":1,"Info":"您当前登录的帐号于[2018-11-12 15:47:51]在IP地址[192.168.255.254]进行登录,现已被迫下线，请退出并重新登录，如确认不是您的操作，请及时修改密码!","Act":"review","IsSuccess":false,"MsgType":null,"Tag":null,"Values":{"token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI3MTJjZmU5Yi01M2VhLTQwN2YtOGVmZC04NWIwY2MyOTY0NWQiLCJyZWdpb25Db2RlIjoiMzcxMzAwIiwicmVnaW9uSWQiOjEsIm9yZ2FuSWQiOjEsImRlcGFydElkIjozMywiY2ZwIjoiNTcxOWE0MmIxZWYzNzZhNjkxMzQxOGE5YWU0NzUyYThlZjExOTdjZCIsImV4cCI6MTU0MjE4MTY4OSwidXNlcklkIjo4MTksInVmcCI6ImluZm90b3AiLCJ0aW1lT3V0IjoxNzI4MDB9.g-u5R3R0s7XOKSzsX73957mHqNCZ6h2O5tWtz_nVhBaDEZAWFlfrX_C7oy69bYbRIPgTu6fr1YxqavOmPgZ9DA","loginConflict":{"user_id":"819","gmt_create":"2018-11-12 15:47:51","ip_address":"192.168.255.254"}}}
					err += "错误信息： 日志 "+review+" \n 返回 "+result+" \n ";
					logger.error("日志审阅失败！错误信息： 日志 "+review+" \n 返回 "+result+" \n ");
				}

			}
		}
		// 如果存在日志审阅异常
		if (StringUtils.isNotEmpty(err)) {
			mailService.saveMail(new MailEntity("工作日志<zhoumh1985@qq.com>", "zmh1812@qq.com", DateUtil.getDate()+"工作日志报错汇总", err,"sendSimpleMail"));
		}
		logger.info("本次未阅处理已完成！");
	}
	
	/**
	 * 根据工作ID进行通过审核操作
	 * @param workLogId 待审核工作ID
	 * @return: boolean 操作是否成功
	 * @author: zhoumh
	 * @version: 创建时间：2018年8月15日 下午5:13:23 
	 * @throws Exception 
	 * @Description:
	 */
	public String saveReview(JSONObject review) throws Exception{
		//{"method":2,"cmd":"review","params":{"api":"worklogreview","act":"review","logId":554,"comment":"","score":5,"queueId":579,"token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJmZTEwMWRjZS1hZjM1LTRhM2EtYTgzNy05NTk2N2FmZmU5NjUiLCJyZWdpb25Db2RlIjoiMzcxMzAwIiwicmVnaW9uSWQiOjEsIm9yZ2FuSWQiOjEsImRlcGFydElkIjozMywiZXhwIjoxNTM1MDg1OTk3LCJ1c2VySWQiOjgxOSwidGltZU91dCI6MTcyODAwfQ.R75tdqExGTMKFyhg1cE0oNJJPoY6Xt2bzMh4CxR6OUxpvADsRcCNXvUnU2YgNa-cyWiq_z1-VQBQoX5LuHkbHQ"}}
		//{"method":2,"cmd":"review","params":{"api":"worklogreview","act":"review","logId":12674,"comment":"","score":5,"queueId":13958,"token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJkYzE5YjQ5Ny0xM2YyLTQ3MDktYWI3MS04MjllYTEwMjgxMzAiLCJyZWdpb25Db2RlIjoiMzcxMzAwIiwicmVnaW9uSWQiOjEsIm9yZ2FuSWQiOjEsImRlcGFydElkIjozMywiY2ZwIjoiNTcxOWE0MmIxZWYzNzZhNjkxMzQxOGE5YWU0NzUyYThlZjExOTdjZCIsImV4cCI6MTU0MTQwMDY2NywidXNlcklkIjo4MTksInVmcCI6ImluZm90b3AiLCJ0aW1lT3V0IjoxNzI4MDB9.iH7NoGSqgR1fzIuCbfqIIs0DZM_PHlGFRTuliGEre24lHEevTUZttwvlmBidtBbaknt5z-6ad1cmy08rKqq9oA","appVer":"4.2.4","termType":0,"systemType":"Win32"}}
		JSONObject params = new JSONObject();
		params.put("api", "worklogreview");
		params.put("act", "review");
		params.put("logId", review.getInteger("logId"));
		params.put("comment", "");
		params.put("score", 5);
		params.put("queueId", review.getInteger("id"));
		params.put("token", token);
		params.put("appVer", "4.2.4");
		params.put("termType", 0);
		params.put("systemType", "Win32");
		JSONObject post = new JSONObject();
		post.put("method", 2);
		post.put("cmd", "review");
		post.put("params", params);
		JSONArray logItems = review.getJSONArray("logItems");
		if (logItems.size()==1) {
			String logContent = logItems.getJSONObject(0).getString("content");
			if (logContent.indexOf("请假")>-1 || logContent.indexOf("调休")>-1) {
				// 如果日志类型为请假，就设置已阅
				params.put("score", 0);
			}
		}
		String result = httpAPIService.doPostJson("http://123.132.252.2:23180/api/v1/worklogreview", JSONObject.toJSONString(post,SerializerFeature.WriteMapNullValue)).getBody();
		return result;
		
	}
	/**
	 * 从返回结果中刷新token
	 * @return: boolean true 更新成功  false 更新失败
	 * @author: zhoumh
	 * @version: 创建时间：2018年11月15日 下午4:40:43 
	 * @Description:
	 */
	private boolean refToken(JSONObject value){
		// 从value中获取token值并更新全局变量
		if(value.getInteger("ErrCode")==0){
			token = value.getJSONObject("Values").getString("token"); //更新token
			return true;
		}
		token = "";
		logger.error("返回错误信息！"+value);
		return false;
	}
	

}
